package com.hcbd.tdwt.base.bd;

import android.app.Activity;
import android.content.Context;
import android.util.Log;
import com.bddomain.models.entity.protocal2_1.BSIMsg;
import com.bddomain.models.entity.protocal2_1.DWRMsg;
import com.bddomain.models.entity.protocal2_1.FKIMsg;
import com.bddomain.models.entity.protocal2_1.GGAMsg;
import com.bddomain.models.entity.protocal2_1.ICIMsg;
import com.bddomain.models.entity.protocal2_1.RMCMsg;
import com.bddomain.models.entity.protocal2_1.TXRMsg;
import com.bddomain.models.entity.protocal2_1.WAAMsg;
import com.bddomain.models.entity.protocalBD3.ACKMsg;
import com.bddomain.models.entity.protocalBD3.COVMsg;
import com.bddomain.models.entity.protocalBD3.DTIMsg;
import com.bddomain.models.entity.protocalBD3.EPIMsg;
import com.bddomain.models.entity.protocalBD3.GBIMsg;
import com.bddomain.models.entity.protocalBD3.GXPMsg;
import com.bddomain.models.entity.protocalBD3.IBDMsg;
import com.bddomain.models.entity.protocalBD3.ICGMsg;
import com.bddomain.models.entity.protocalBD3.ICPMsg;
import com.bddomain.models.entity.protocalBD3.ICWMsg;
import com.bddomain.models.entity.protocalBD3.ICZMsg;
import com.bddomain.models.entity.protocalBD3.LZPMsg;
import com.bddomain.models.entity.protocalBD3.MCHMsg;
import com.bddomain.models.entity.protocalBD3.OBDMsg;
import com.bddomain.models.entity.protocalBD3.PWIMsg;
import com.bddomain.models.entity.protocalBD3.QPIMsg;
import com.bddomain.models.entity.protocalBD3.QRIMsg;
import com.bddomain.models.entity.protocalBD3.SNPMsg;
import com.bddomain.models.entity.protocalBD3.TCIMsg;
import com.bddomain.models.entity.protocalBDHZ.BDHZMsg;
import com.bddomain.repository.tools.BDMethod;

import com.example.bdcomsdk.handler.COMManager;
import com.example.bdcomsdk.impl.AgentCOMListener;


import com.hcbd.tdwt.MainApp;
import com.hcbd.tdwt.base.BdManager;
import com.hcbd.tdwt.base.BeidouBoxParams;
import com.hcbd.tdwt.base.Constant;

import com.hcbd.tdwt.util.FileUtil;
import com.hcbd.tdwt.util.FileUtils;
import com.pangu.bdsdk2021.entity.terminalone.BDFKInfo;
import com.pangu.bdsdk2021.entity.terminalone.BDTXInfo;
import com.pangu.bdsdk2021.entity.terminalthree.BDSXXInfo;
import com.pangu.bdsdk2021.entity.terminalthree.BDSnrInfo;

import org.greenrobot.eventbus.EventBus;

import java.io.UnsupportedEncodingException;

import static java.lang.Thread.sleep;

public class BDNotificationManager  implements AgentCOMListener {
    private static BDNotificationManager bdNotificationManager;
    private Context mContext;
    private BdManager bdManager;
    private BDNotificationManager(){
        bdManager=BdManager.getInstance();

    }
    public static BDNotificationManager getInstance() {
        if (bdNotificationManager == null) {
            bdNotificationManager = new BDNotificationManager();
        }
        return bdNotificationManager;
    }

    public  void openBdcom(Context context) {
        this.mContext = context;
        BeidouBoxParams.isBoxConnectNormal = true;
        COMManager.getInstance().agentListeners.add(this);
        COMManager.getInstance().openBDCOM(mContext.getApplicationContext());

        //设置北三特征
        BeidouBoxParams.card_model=3;
        BeidouBoxParams.horizontalAxis= 21;
        BeidouBoxParams.verticalAxis=4;
        BeidouBoxParams.middleSignal = 4;
        MainApp.getInstance().showLoading("打开北斗服务中");
        new Thread(() -> {
            try {
                sleep(1000);
                int count = 20;
                while (BeidouBoxParams.userCardNumber.equals("") && count > 0) {
                    COMManager.getInstance().sendCCICR(0,"00");
                    sleep(1500);
                    count--;
                }

                if (count == 0){
                    MainApp.getInstance().showMsg("读取北斗信息失败");
                    bdNotificationManager.clsoeBdcom();
                    return;
                }
                String cmd = "CCRMO,PWI,2,5";
                COMManager.getInstance().send(getCMD(cmd));

                MainApp.getInstance().hideLoading();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
    }

    public static byte [] getCMD(String cmd){
        byte[] tmp  = cmd.getBytes();
        byte ret = BDMethod.CheckByte(tmp,tmp.length);
        String crc = BDMethod.castByteToHexString(ret);
        String result = "$" + cmd + "*" + crc + "\r\n";
        return  result.getBytes();
    }

    /**
     * 停止接收将数据放入接收缓存
     */
    public void clsoeBdcom() {
        BeidouBoxParams.isBoxConnectNormal = false;
        if(mContext==null){
            return;
        }
        COMManager.getInstance().closeBDCOM(this.mContext.getApplicationContext());
        COMManager.getInstance().agentListeners.remove(this);
        BeidouBoxParams.init();
        EventBus.getDefault().post("onConnectError");
    }

    public void CCICA(){
        COMManager.getInstance().sendCCICA();
    }

    public void CCTXA(String number, int mode, String content){
        COMManager.getInstance().sendCCTXA(number,1,mode,content);
    }
    public void CCTCQ(String number, int frePoint, int mode, String content){
        writeText("CCTCQ_send:"+content);
        try {
            COMManager.getInstance().sendCCTCQ(number,frePoint,1, mode, content,0);
        }catch (UnsupportedEncodingException e){
            MainApp.getInstance().showMsg("发射异常"+e.getLocalizedMessage());
        }

    }

    @Override
    public void onBDTXR(TXRMsg txrMsg) {
        writeText("txrMsg:"+txrMsg.getTxrStr());
        BDTXInfo bdtxInfo=new BDTXInfo();
        bdtxInfo.content=txrMsg.getMsgContent();
        bdtxInfo.fromNumber= Integer.parseInt(txrMsg.getUserID());
        bdManager.onTXInfo(bdtxInfo);
    }

    @Override
    public void onBDBSI(BSIMsg bsiMsg) {
        writeText("bsi:"+bsiMsg.getBsiStr());
        Log.e("bsi:",bsiMsg.getBsiStr());
        BDSnrInfo.obj.s1 = Integer.parseInt(BSIMsg.getBpow1());
        BDSnrInfo.obj.s2 = Integer.parseInt(BSIMsg.getBpow2());
        BDSnrInfo.obj.s3 = Integer.parseInt(BSIMsg.getBpow3());
        BDSnrInfo.obj.s4 = Integer.parseInt(BSIMsg.getBpow4());
        BDSnrInfo.obj.s5 = Integer.parseInt(BSIMsg.getBpow5());
        BDSnrInfo.obj.s6 = Integer.parseInt(BSIMsg.getBpow6());
        BDSnrInfo.obj.s7 = Integer.parseInt(BSIMsg.getBpow7());
        BDSnrInfo.obj.s8 = Integer.parseInt(BSIMsg.getBpow8());
        BDSnrInfo.obj.s9 = Integer.parseInt(BSIMsg.getBpow9());
        BDSnrInfo.obj.s10= Integer.parseInt(BSIMsg.getBpow10());
        BDSnrInfo.obj.s11 = Integer.parseInt(BSIMsg.getBpow11());
        BDSnrInfo.obj.s12 = Integer.parseInt(BSIMsg.getBpow12());
        BDSnrInfo.obj.s13 = Integer.parseInt(BSIMsg.getBpow13());
        BDSnrInfo.obj.s14 = Integer.parseInt(BSIMsg.getBpow14());
        BDSnrInfo.obj.s15 = Integer.parseInt(BSIMsg.getBpow15());
        BDSnrInfo.obj.s16 = Integer.parseInt(BSIMsg.getBpow16());
        BDSnrInfo.obj.s17 = Integer.parseInt(BSIMsg.getBpow17());
        BDSnrInfo.obj.s18 = Integer.parseInt(BSIMsg.getBpow18());
        BDSnrInfo.obj.s19 = Integer.parseInt(BSIMsg.getBpow19());
        BDSnrInfo.obj.s20 = Integer.parseInt(BSIMsg.getBpow20());
        BDSnrInfo.obj.s21 = Integer.parseInt(BSIMsg.getBpow21());
        //由于福大的北三手持机信号转换成北二的值，信号转换贼差，需强行提升信号强度
        BeidouBoxParams.BeamSignalLifting();
        bdManager.onBDSnrInfo(BDSnrInfo.obj);
    }

    @Override
    public void onBDICI(ICIMsg iciMsg) {
        writeText("ICI:"+iciMsg.getIciStr());
        BDSXXInfo bdsxxInfo=new BDSXXInfo();
        bdsxxInfo.user_id=iciMsg.getICnum();
        bdsxxInfo.regional_service_frequency=iciMsg.getFreq();

        bdsxxInfo.cardType=iciMsg.getLevel();
        bdManager.onBDSXXInfo(bdsxxInfo);
    }

    @Override
    public void onBDFKI(FKIMsg fkiMsg) {
        writeText("fki:"+fkiMsg.getFkidata());

        BDFKInfo bdfkInfo=new BDFKInfo();
        if (fkiMsg.getComExeSituation()) {
            bdfkInfo.state=Constant.Y;
        } else {
            bdfkInfo.state=Constant.N;
        }
        bdManager.onFKInfo(bdfkInfo);

    }

    @Override
    public void onBDDWR(DWRMsg dwrMsg) {

    }

    @Override
    public void onBDERR() {

    }

    @Override
    public void onRMC(RMCMsg rmcMsg) {

    }

    @Override
    public void onGGA(GGAMsg ggaMsg) {

    }

    @Override
    public void onBDHZ(BDHZMsg bdhzMsg) {

    }

    @Override
    public void onWAA(WAAMsg waaMsg) {

    }

    @Override
    public void onStrSend(String s) {

    }

    @Override
    public void onStrRec(byte[] bytes) {

    }

    @Override
    public void onStrGpsRec(byte[] bytes) {

    }

    @Override
    public void onStrBDRec(final byte[] bytes) {
        try {
            String str = new String(bytes,"GB2312");
            Log.e("---BLE", str);
            ((Activity)mContext).runOnUiThread(new Runnable() {
                public void run() {
                    if (str.contains("BDFKI")){
                        onBDFKI(new com.bddomain.models.entity.protocalBD3.FKIMsg(bytes));
                    }
                }
            });
        }catch (UnsupportedEncodingException e){
            Log.e("---BLE", "onStrBDRec UnsupportedEncodingException:"+e.getLocalizedMessage());
        }
    }

    @Override
    public void onBDACK(ACKMsg ackMsg) {

    }

    @Override
    public void onBDCOV(COVMsg covMsg) {

    }

    @Override
    public void onBDDTI(DTIMsg dtiMsg) {

    }

    @Override
    public void onBDEPI(EPIMsg epiMsg) {

    }

    @Override
    public void onBDFKI(com.bddomain.models.entity.protocalBD3.FKIMsg fkiMsg) {
        writeText("fki:"+fkiMsg.getFkidata());
        Log.e("onBDFKI-北三",fkiMsg.getInboundEmissionType());
        if (!fkiMsg.getInboundEmissionType().equals("TCQ")) return;
        BDFKInfo bdfkInfo=new BDFKInfo();
        bdfkInfo.state=fkiMsg.getLaunchSituation();
        bdManager.onFKInfo(bdfkInfo);

    }

    @Override
    public void onBDGBI(GBIMsg gbiMsg) {

    }

    @Override
    public void onBDIBD(IBDMsg ibdMsg) {

    }

    @Override
    public void onBDICG(ICGMsg icgMsg) {

    }

    @Override
    public void onBDICP(ICPMsg icpMsg) {
        writeText("icp:"+icpMsg.getIcpdata());
        Log.e("ICPMsg:",icpMsg.getIcpdata());
        BeidouBoxParams.ASecretIdentity=icpMsg.getASecretIdentity();

        BDSXXInfo bdsxxInfo=new BDSXXInfo();
        bdsxxInfo.user_id=icpMsg.getIDNumber();
        bdsxxInfo.regional_service_frequency=icpMsg.getRDSS_ServiceFrequency();
        bdsxxInfo.cardType=icpMsg.getRDSS_CommunicationLengthLevel();
        bdManager.onBDSXXInfo(bdsxxInfo);

    }

    @Override
    public void onBDICW(ICWMsg icwMsg) {

    }

    @Override
    public void onBDICZ(ICZMsg iczMsg) {

    }

    @Override
    public void onBDMCH(MCHMsg mchMsg) {

    }

    @Override
    public void onBDOBD(OBDMsg obdMsg) {

    }

    @Override
    public void onBDPWI(PWIMsg pwiMsg) {
        writeText("pwi:"+pwiMsg.getPwidata());
        Log.e("onBDPWI",pwiMsg.getNumberOfOutboundBeamlocksInRDSS_NewSystem());
        int s21[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
        for (int i =0 ;i < pwiMsg.getRDSS_NewSystem().size(); i++){
            PWIMsg.NOISE noise = pwiMsg.getRDSS_NewSystem().get(i);
            int id = Integer.parseInt(noise.getNO());
            if (id > 21) continue;
            int number = Integer.parseInt(noise.getS1());
            s21[id-1] = number;
        }
        BDSnrInfo.obj.s1 = s21[0];
        BDSnrInfo.obj.s2 = s21[1];
        BDSnrInfo.obj.s3 = s21[2];
        BDSnrInfo.obj.s4 = s21[3];
        BDSnrInfo.obj.s5 = s21[4];
        BDSnrInfo.obj.s6 = s21[5];
        BDSnrInfo.obj.s7 = s21[6];
        BDSnrInfo.obj.s8 = s21[7];
        BDSnrInfo.obj.s9 = s21[8];
        BDSnrInfo.obj.s10 = s21[9];
        BDSnrInfo.obj.s11 = s21[10];
        BDSnrInfo.obj.s12 = s21[11];
        BDSnrInfo.obj.s13 = s21[12];
        BDSnrInfo.obj.s14 = s21[13];
        BDSnrInfo.obj.s15 = s21[14];
        BDSnrInfo.obj.s16 = s21[15];
        BDSnrInfo.obj.s17 = s21[16];
        BDSnrInfo.obj.s18 = s21[17];
        BDSnrInfo.obj.s19 = s21[18];
        BDSnrInfo.obj.s20 = s21[19];
        BDSnrInfo.obj.s21 = s21[20];
        bdManager.onBDSnrInfo(BDSnrInfo.obj);
    }

    @Override
    public void onBDQRI(QRIMsg qriMsg) {

    }

    @Override
    public void onBDTCI(TCIMsg tciMsg) {
        writeText("tciMsg:"+tciMsg.getTcidata());
        BDTXInfo bdtxInfo=new BDTXInfo();
        bdtxInfo.messageType=Integer.parseInt(tciMsg.getCodingCategories());
        bdtxInfo.content=tciMsg.getCommunicationData();
        bdtxInfo.fromNumber=Integer.parseInt(tciMsg.getTransmittingTheID());
        bdManager.onTXInfo(bdtxInfo);

    }

    @Override
    public void onBDQPI(QPIMsg qpiMsg) {

    }

    @Override
    public void onBDGXP(GXPMsg gxpMsg) {

    }

    @Override
    public void onBDLZP(LZPMsg lzpMsg) {

    }

    @Override
    public void onBDSNP(SNPMsg snpMsg) {

    }
    private static String filePath = FileUtil.getLogFile();
    public static void writeText(final String content){
        FileUtils.writeFile(filePath,content);
    }
}
